package net.fpeg.kotlin.msa.auth.service

import org.springframework.stereotype.Service
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import java.util.*

@Service
class JwtService {
    fun Calendar.adds(field: Int, amount: Int): Calendar {
        this.add(field, amount)
        return this
    }

    fun encode(id: Long): String =
            JWT.create()
                    .withHeader(mapOf("alg" to "HS256", "typ" to "JWT"))
                    .withClaim("iss", "Service")
                    .withClaim("aud", "APP")
                    .withClaim("id", id)
                    .withIssuedAt(Date())
                    .withExpiresAt(Calendar.getInstance().adds(Calendar.DATE, 10).time)
                    .sign(Algorithm.HMAC256("SECRET"))

    fun decode(jwt: String) = try {
        JWT.require(Algorithm.HMAC256("SECRET")).build().verify(jwt).getClaim("id").asLong()
    } catch (ex: Exception) {
        null
    }


}